<template>
  <div>
    <FixedOperation>
      <!-- 内容 -->
      <el-row :gutter="20">
        <!--产品分类-->
        <el-col :span="24" :xs="24">
          <div class="text-right">
            <el-button
              type="primary"
              plain
              @click="handleSubmit('保存')"
              v-if="formData.isSubmit == '0'"
              >保存</el-button
            >
            <el-button type="primary" @click="handleSubmit('提交')"
              >提交</el-button
            >
            <el-button type="primary" plain @click="handleReturn"
              >返回</el-button
            >
            <!-- <el-button icon="Refresh" @click="handleReset(form)"
              >重置</el-button
            > -->
          </div>
        </el-col>
      </el-row>
    </FixedOperation>
    <div class="app-container workReport-form">
      <el-form
        ref="form"
        :model="formData"
        label-width="140px"
        :rules="formRules"
      >
        <el-row>
          <el-col :span="16" :offset="3">
            <el-form-item label="报告类型" prop="reportType">
              <el-radio-group
                v-model="formData.reportType"
                @change="changeReportType"
              >
                <el-radio-button
                  v-for="item in report_type"
                  :key="item.value"
                  :label="item.value"
                  >{{ item.label }}</el-radio-button
                >
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="13" :offset="3">
            <el-form-item
              label="报告日期"
              :prop="
                formData.reportType == '0' ? 'reportStartDate' : 'reportDateArr'
              "
            >
              <el-date-picker
                style="width: 100%"
                v-model="formData.reportStartDate"
                type="date"
                placeholder="报告日期"
                value-format="YYYY-MM-DD"
                v-if="formData.reportType == '0'"
              />
              <el-date-picker
                style="width: 100%"
                v-model="formData.reportDateArr"
                type="daterange"
                range-separator="-"
                start-placeholder="报告开始日期"
                end-placeholder="报告结束日期"
                value-format="YYYY-MM-DD"
                v-else
              />
            </el-form-item>
          </el-col>
          <el-col :offset="1" :span="2">
            <el-button type="primary" @click="queryTask">提取任务</el-button>
          </el-col>
          <el-col :span="16" :offset="3">
            <el-form-item label="工作总结" prop="summary">
              <!-- <el-input v-model="formData.summary" /> -->
              <editor
                class="w-full"
                v-model="formData.summary"
                :min-height="192"
              />
            </el-form-item>
          </el-col>
          <el-col :span="16" :offset="3" v-if="formData.reportType !== '0'">
            <el-form-item label="工作计划" prop="plan">
              <el-input type="textarea" rows="8" v-model="formData.plan" />
              <!-- <editor
                class="w-full"
                v-model="formData.plan"
                :min-height="192"
              /> -->
            </el-form-item>
          </el-col>
          <el-col :span="16" :offset="3">
            <el-form-item label="上传附件" prop="workReportAttachmentList">
              <!-- 
                v-model:file-list="formData.workReportAttachmentList" -->
              <el-upload
                class="upload-demo"
                action="#"
                :before-upload="beforeAvatarUpload1"
                :http-request="requestFile1"
                accept=".rar, .zip, .doc, .docx, .pdf"
                :limit="10"
                :show-file-list="false"
              >
                <!-- 
                accept=".rar, .zip, .doc, .docx, .pdf, .xls, .xlsx, .ppt, .pptx,.gif, .jpg, .jpeg, .png" -->
                <el-button type="default" style="font-size: 14px"
                  ><el-icon><UploadFilled /></el-icon>上传附件</el-button
                >
                <template #tip>
                  <div class="el-upload__tip float-right">
                    支持格式.rar .zip .doc .docx .pdf ，单个文件不能超过200MB
                  </div>
                </template>
              </el-upload>
              <div class="text-14px mt-10px" style="width: 100%">
                <div
                  v-for="(item, index) in formData.workReportAttachmentList"
                  :key="item.fileName"
                >
                  <el-link :href="item.url" :underline="false" type="primary">{{
                    item.origFileName
                  }}</el-link>
                  <el-button text plain @click="delFileName1(index)"
                    >删除</el-button
                  >
                </div>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="16" :offset="3">
            <el-form-item label="主送给" prop="_reviewUserArr">
              <el-select
                class="w-full"
                v-model="formData._reviewUserArr"
                :multiple="true"
                placeholder="指定人员"
                @focus="selectUserFn('reviewUserArr')"
              >
                <el-option
                  v-for="item in userOption['reviewUserArr']"
                  :key="item.uuid"
                  :label="item.label"
                  :value="item.uuid"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="16" :offset="3">
            <el-form-item label="抄送给" prop="_copyUserArr">
              <el-select
                class="w-full"
                v-model="formData._copyUserArr"
                :multiple="true"
                placeholder="指定人员"
                @focus="selectUserFn('copyUserArr')"
              >
                <el-option
                  v-for="item in userOption['copyUserArr']"
                  :key="item.uuid"
                  :label="item.label"
                  :value="item.uuid"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <!-- 人员弹出框下拉框 -->
    <SelectDialog
      :dialog-param="dialogParam"
      @ok="selectDialogData"
      @close="
        val => {
          dialogParam.isDialog = false
        }
      "
    />
  </div>
</template>
<script setup name="WorkReportForm">
import { useRouter, useRoute } from 'vue-router'
import useCommonStore from '@/store/modules/common'
import useUserStore from '@/store/modules/user'
import { getWorkReport, setWorkReport, listTask } from '@/api/workReport/index'
import { uploadFile, delFile } from '@/api/salesManage/contractManage'
import useTagsViewStore from '@/store/modules/tagsView'
import {
  skipToError,
  getTreeNodeByParam,
  getPricipalId,
  viewFile
} from '@/utils/commo'
import { getMondayDate } from '@/utils/date'
import { format, startOfMonth, endOfMonth } from 'date-fns'
import { addManage } from '@/api/system/notice'
import { parseTime } from '@/utils/ruoyi'
const router = useRouter()
const route = useRoute()
const commonStore = useCommonStore()
const { proxy, type } = getCurrentInstance()
const companyData = ref([])
commonStore.getCompanyData().then(e => {
  companyData.value = e
})

const { report_type, sys_work_report_submit } = proxy.useDict(
  'report_type', //  --报告类型
  'sys_work_report_submit' //是否已提交
)

const props = defineProps({
  workReportData: {
    type: Object,
    require: true,
    default: null
  }
})

const data = reactive({
  formData: {
    isSubmit: '0', //是否提交1已提交，0未提交
    workReportAttachmentList: [], //附件
    reportDateArr: [],
    reportStartDate: proxy.parseTime(new Date(new Date().getTime())),
    reportType: '1',
    _reviewUserArr: []
  },
  userOption: { reviewUserArr: [], copyUserArr: [] }, //人员选择下拉
  formRules: {
    reportDateArr: [
      {
        required: true,
        message: '请选择时间',
        trigger: ['blur', 'change']
      }
    ],
    reportStartDate: [
      {
        required: true,
        message: '请选择时间',
        trigger: ['blur', 'change']
      }
    ],
    summary: [
      {
        required: true,
        message: '请输入工作总结',
        trigger: ['blur', 'change']
      }
      // {
      //   validator: aaaa,
      //   trigger: 'blur'
      // }
    ],
    // plan: [
    //   {
    //     required: true,
    //     message: '请输入工作计划',
    //     trigger: ['blur', 'change']
    //   }
    // ],
    _reviewUserArr: [
      {
        required: true,
        message: '请选择指定人员',
        trigger: ['change']
      }
    ]
  },
  dialogParam: {}
})
const { formData, userOption, formRules, dialogParam } = toRefs(data)

watch(
  () => route.query.workReportId,
  () => {
    if (route.query.workReportId && route.name == type.name) {
      getFormData(route.query.workReportId)
    }
  },
  {
    immediate: true
  }
)

// 变化报告类型时
function changeReportType(val) {
  switch (val) {
    case '0':
      formData.value.reportStartDate = proxy.parseTime(
        new Date(new Date().getTime())
      )
      break
    case '1':
      formData.value.reportDateArr = [
        parseTime(getMondayDate(new Date()).monStartday, '{y}-{m}-{d}'),
        parseTime(getMondayDate(new Date()).monEndDay, '{y}-{m}-{d}')
      ]
      break
    case '2':
      formData.value.reportDateArr = [
        format(startOfMonth(new Date()), 'yyyy-MM-dd'),
        format(endOfMonth(new Date()), 'yyyy-MM-dd')
      ]
      break
  }
}
// 初始化
function init() {
  changeReportType(formData.value.reportType)
}
/** 获取产品详情
 * @param {number}  id 表单id
 */
function getFormData(id) {
  return new Promise((resolve, reject) => {
    getWorkReport(id).then(async res => {
      let resData = {}
      resData = res.data
      formData.value = { ...formData.value, ...resData }
      resolve(res)
      // 获取主送给
      if (
        formData.value.reviewUserArr &&
        formData.value.reviewUserArr.length > 0
      ) {
        await getDefaultUserInfo(
          formData.value.reviewUserArr,
          '_reviewUserArr',
          'reviewUserArr'
        )
      }
      // 获取抄送给
      if (formData.value.copyUserArr && formData.value.copyUserArr.length > 0) {
        await getDefaultUserInfo(
          formData.value.copyUserArr,
          '_copyUserArr',
          'copyUserArr'
        )
      }
    })
  })
}
// 保存
function handleSubmit(e) {
  // 批阅人
  if (
    formData.value._reviewUserArr &&
    formData.value._reviewUserArr.length > 0
  ) {
    formData.value.reviewUserArr = getPricipalId(
      userOption.value['reviewUserArr'],
      formData.value._reviewUserArr
    )
  }
  // 抄送人
  if (formData.value._copyUserArr && formData.value._copyUserArr.length > 0) {
    formData.value.copyUserArr = getPricipalId(
      userOption.value['copyUserArr'],
      formData.value._copyUserArr
    )
  }
  if (e == '提交') {
    const isSubmit = formData.value.isSubmit
    const formParam = { ...formData.value, isSubmit: '1' }
    proxy.$refs.form.validate((valid, done, msg) => {
      if (valid) {
        setWorkReport(formParam).then(res => {
          handleReturn()
          getFormData(res.data.id).then(e => {
            console.log('e==>', e)
            let title = ''
            if (isSubmit === '0') {
              if (formData.value.reportType !== '0') {
                title = `${e.data.createName}${proxy.parseTime(
                  e.data.reportStartDate,
                  '{y}-{m}-{d}'
                )}至${proxy.parseTime(
                  e.data.reportEndDate,
                  '{y}-{m}-{d}'
                )}的工作${proxy.selectDictLabel(
                  report_type.value,
                  e.data.reportType
                )}`
              } else {
                title = `${e.data.createName}${proxy.parseTime(
                  e.data.reportStartDate,
                  '{y}-{m}-{d}'
                )}的工作${proxy.selectDictLabel(
                  report_type.value,
                  e.data.reportType
                )}`
              }
            } else {
              if (formData.value.reportType !== '0') {
                title = `${e.data.createName}更新了${proxy.parseTime(
                  e.data.reportStartDate,
                  '{y}-{m}-{d}'
                )}至${proxy.parseTime(
                  e.data.reportEndDate,
                  '{y}-{m}-{d}'
                )}的工作${proxy.selectDictLabel(
                  report_type.value,
                  e.data.reportType
                )}`
              } else {
                title = `${e.data.createName}更新了${proxy.parseTime(
                  e.data.reportStartDate,
                  '{y}-{m}-{d}'
                )}的工作${proxy.selectDictLabel(
                  report_type.value,
                  e.data.reportType
                )}`
              }
            }
            console.log('title==>', title)
            let mesVoData = {
              businessId: '工作报告-' + e.data.id, //业务ID
              content: title, //待办内容
              followDate: undefined, //跟进日期
              followType: undefined, //跟进方式
              impSign: '2', //重要程度:0-非常重要，1-重要，2-一般
              receiver: '', //接收人
              receiverName: undefined, //接收人中文
              reminderMethod: '0', //提醒方式:0-系统站内，1-邮箱，2-短信，允许多个并存，例如:0,1,2
              sendTime: e.data.updateTime, //发送时间
              sender: e.data.updateName, //发送人
              serviceType: '18', //业务类型:18-批阅工作报告，19-抄送工作报告
              title: title, //待办标题
              type: '0', //待办类型:0-普通，1-流程
              urgFlag: '2', //紧急程度:0-非常紧急，1-紧急，2-一般
              url: `/rsgl/other/workReportDetails?workReportId=${e.data.id}`, //待办链接(多链接用英文逗号隔开)
              urlName: '前往处理' //待办链接名称(多链接名称用英文逗号隔开)
            }
            if (e.data.reviewUser) {
              addManage({
                ...mesVoData,
                ...{ receiver: e.data.reviewUser, serviceType: '18' }
              })
            }
            if (e.data.copyUser) {
              addManage({
                ...mesVoData,
                ...{ receiver: e.data.copyUser, serviceType: '19' }
              })
            }
          })
          console.log('formData.value==>', formData.value)
        })
      }
    })
  } else if (e == '保存') {
    // proxy.$refs.form.validate((valid, done, msg) => {
    //   if (valid) {
    const formParam = { ...formData.value, isSubmit: '0' }
    setWorkReport(formParam).then(res => {
      // 保存接口才有
      proxy.useReturn(
        '',
        () => {
          //返回上一步
          handleReturn()
        },
        async () => {
          //继续
        }
      )
      getFormData(res.data.id)
    })
    //   }
    // })
  }
}

function handleReturn() {
  useTagsViewStore().delView(router.currentRoute.value)
  router.go(-1)
  // router.push({ path: url, query: data })
  //   proxy.$refs.form.clearValidate()
}

/**文件上传 限制条件
 *
 * @param {*} rawFile
 */
function beforeAvatarUpload1(rawFile) {
  const ext = rawFile.name.substring(rawFile.name.lastIndexOf('.'))
  const allowType = ['.rar', '.zip', '.doc', '.docx', '.pdf'].indexOf(ext) > -1
  const isLt2M = rawFile.size / 1024 / 1024 < 200

  if (!allowType) {
    proxy.$message.error('上传文件只能是.rar、.zip、.doc、.docx、.pdf格式!')
  } else if (!isLt2M) {
    proxy.$message.error('上传文件大小不能超过 200MB!')
  }
  return allowType && isLt2M
}
// 上传附件
function requestFile1(params) {
  let uploadData = new FormData()
  uploadData.append('file', params.file)
  // uploadData.append('bucketName', 'article')
  uploadFile(uploadData).then(res => {
    if (res.code === 200) {
      proxy.$modal.msgSuccess(`${res.data.origFileName}上传成功`)
      console.log('formData.value==>', formData.value)
      formData.value.workReportAttachmentList.push(res.data)
      console.log(
        'formData.value.workReportAttachmentList==>',
        formData.value.workReportAttachmentList
      )
    }
  })
}
// 删除附件
async function delFileName1(index) {
  try {
    proxy.$modal.confirm('是否删除该文件').then(async () => {
      // let fule = {
      //   // bucketName: 'article',
      //   fileName: formData.value.workReportAttachmentList[index].fileName
      // }
      const res = await delFile(
        formData.value.workReportAttachmentList[index].fileName
      )
      if (res.code === 200) {
        formData.value.workReportAttachmentList.splice(index, 1)
        proxy.$modal.msgSuccess(res.data)
      }
    })
  } catch (error) {
    proxy.$modal.msgError(error)
  }
}
// 预览文件
function viewFiles(url) {
  viewFile(url, useUserStore().userInfo.nickName)
}

/**
 * 人员选择
 * @param keyName copyUserArr:抄送人  reviewUserArr:批阅人
 */
function selectUserFn(keyName) {
  switch (keyName) {
    case 'reviewUserArr':
      dialogParam.value.type = keyName
      dialogParam.value.title = '请选择批阅人'
      dialogParam.value.isDialog = true
      dialogParam.value.multiple = true
      dialogParam.value.checkStrictly = false
      dialogParam.value.nodeKey = 'uuid'
      dialogParam.value.defaultCheckedKeys = formData.value['_' + keyName]
      dialogParam.value.dataType = 'person'
      break
    case 'copyUserArr':
      dialogParam.value.type = keyName
      dialogParam.value.title = '请选择抄送人'
      dialogParam.value.isDialog = true
      dialogParam.value.multiple = true
      dialogParam.value.checkStrictly = false
      dialogParam.value.nodeKey = 'uuid'
      dialogParam.value.defaultCheckedKeys = formData.value['_' + keyName]
      dialogParam.value.dataType = 'person'
      break
  }
}

// 人员选择确定
const selectDialogData = val => {
  switch (val.type) {
    case 'reviewUserArr':
      userOption.value.reviewUserArr = val.selectData
      // formData.value.transactionName = val.labelData.toString()
      formData.value._reviewUserArr = val.defaultCheckedKeys
      break
    case 'copyUserArr':
      userOption.value.copyUserArr = val.selectData
      formData.value._copyUserArr = val.defaultCheckedKeys
      break
  }
}

/**
 * 根据当前用户id转为uuid（id前加u）
 * @param val 输入用户的id
 * @param fieldName 需要赋值的字段
 * @param selectArr 用户的字典
 */
async function getDefaultUserInfo(val, fieldName, selectArr) {
  let userTree = await commonStore.getUseTreeData()
  userOption.value[selectArr] = []
  let id = ''
  if (val) {
    id = val
  }
  if (Array.isArray(id)) {
    formData.value[fieldName] = []
    id.forEach(item => {
      let obj = getTreeNodeByParam(userTree, item, 'id', [])
      userOption.value[selectArr].push(...obj)
      formData.value[fieldName].push(obj[0].uuid)
    })
  } else {
    //根据当前用户id获取uuid
    let obj = getTreeNodeByParam(userTree, id, 'id', [])
    userOption.value[selectArr] = obj
    formData.value[fieldName] = obj[0].uuid
  }
}

const taskList = ref([])
// 查询日期内任务列表
function queryTask() {
  if (!formData.value.reportDateArr || !formData.value.reportDateArr.length) {
    proxy.$modal.msgWarning('请先选择日期')
    return false
  }
  const params = {
    startTime: formData.value.reportDateArr[0],
    endTime: formData.value.reportDateArr[1]
  }
  listTask(params)
    .then(res => {
      console.log(res, '123')
      if (Array.isArray(res) && res.length) {
        formData.value.summary = res
          .map(v => {
            let str = ''
            str += `<span>${v.businessName}</span>`
            v.taskReportDetail.forEach((item, index) => {
              str += `<span>${index + 1}、${item.title}  (${
                item.schedule ? item.schedule : '0%'
              } ${
                item.realEndTime
                  ? item.realEndTime.replace(/\d{2}:\d{2}:\d{2}/, '')
                  : item.endTime.replace(/\d{2}:\d{2}:\d{2}/, '')
              })</span>`
            })
            str += '<br />'
            console.log(str)
            return str
          })
          .toString()
          .replace(/,/g, '')

        formData.value.plan = res
          .filter(v => {
            v.taskReportDetail = v.taskReportDetail.filter(
              item =>
                (item.schedule && item.schedule !== '100%') || !item.schedule
            )
            return v.taskReportDetail.length
          })
          .map(v => {
            let str = ''
            str += `${v.businessName}\r`
            v.taskReportDetail.forEach((item, index) => {
              str += `${index + 1}、${item.title}\r`
            })
            str += '\n\r'
            console.log(str)
            return str
          })
          .toString()
          .replace(/,/g, '')
      }

      proxy.$modal.msgSuccess('提取成功')
    })
    .catch(() => {
      taskList.value = []
    })
}

init()
</script>
<style scoped></style>
